<template>
  <div class="template-root-div">
    <div class="left-table">
      <div class="main">
        <mine-title>诊断算法模板</mine-title>
        <div class="content">
          <div class="block-header">
            <div class="block-header-left">
              <mine-button type="primary" @click="addDict()"
                ><i class="iconfont icon-add-line"></i>新增算法源码
              </mine-button>
              <mine-button
                @click="deleteDict"
                secondary
                :disabled="!dictMultipleSelection.length"
                ><i class="iconfont icon-delete-line"></i>删除
              </mine-button>
              <mine-button
                type="primary"
                secondary
                @click="loadDictData(true, true)"
                ><i class="iconfont icon-reset-line"></i>刷新
              </mine-button>
            </div>
            <div class="block-header-right"></div>
          </div>
          <el-table
            class="table"
            :data="dictTableData"
            style="width: 100%"
            v-loading="dictLoading"
            @selection-change="handleDictSelectionChange"
            @row-click="dictRowClick"
            ref="multipleTable"
          >
            <el-table-column type="selection" width="45"></el-table-column>
            <el-table-column label="序号" show-overflow-tooltip width="60">
              <template slot-scope="scope">
                <span
                  >{{ scope.$index + (dictCurrentPage - 1) * dictPageSize + 1 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="算法名称"
              prop="algoName"
              show-overflow-tooltip
            >
              <template slot="header">
                <span>算法名称</span>
                <mine-table-search
                  @searchSubmit="searchDictSubmit"
                  name="algoName"
                ></mine-table-search>
              </template>
            </el-table-column>
            <el-table-column
              label="算法编码"
              prop="algoCode"
              show-overflow-tooltip
            >
              <template slot="header">
                <span>算法编码</span>
                <mine-table-search
                  @searchSubmit="searchDictSubmit"
                  name="algoCode"
                ></mine-table-search>
              </template>
            </el-table-column>
            <!-- <el-table-column
              label="算法语言"
              prop="language"
              show-overflow-tooltip
            >
              <template slot="header">
                <span>算法语言</span>
                <mine-table-search
                  @searchSubmit="searchDictSubmit"
                  name="language"
                ></mine-table-search>
              </template>
            </el-table-column> -->
            <el-table-column
              label="实现功能"
              prop="purpose"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              label="生成次数"
              prop="counts"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- <mine-button type="text" @click="checkDict(scope.row)"
                  >详情</mine-button
                > -->
                <mine-button type="text" @click="editDetectList(scope.row)"
                  >详情</mine-button
                >
              </template>
            </el-table-column>
          </el-table>
          <mine-pagination
            @numberChange="dictNumberChange"
            :total="detectTotal"
            :page-size="dictPageSize"
            :current-page="dictCurrentPage"
          >
          </mine-pagination>
        </div>
      </div>
    </div>
    <div class="right-table">
      <div class="main">
        <mine-title>算法文件</mine-title>
        <div class="content">
          <div class="block-header">
            <div class="block-header-left">
              <mine-button
                type="primary"
                @click="addOption()"
                :disabled="!currentDetectLeftRowId"
                ><i class="iconfont icon-upload-line"></i>文件上传
              </mine-button>
              <mine-button
                @click="deleteOption"
                secondary
                :disabled="!optionMultipleSelection.length"
                ><i class="iconfont icon-delete-line"></i>删除
              </mine-button>
              <mine-button
                type="primary"
                secondary
                @click="loadOptionData(true, true)"
              >
                <i class="iconfont icon-reset-line"></i>刷新
              </mine-button>
            </div>
            <div class="block-header-right"></div>
          </div>
          <el-table
            class="table"
            :data="optionTableData"
            style="width: 100%"
            v-loading="optionLoading"
            @selection-change="handleOptionSelectionChange"
            @row-click="dictOptionClick"
            ref="multipleTable"
          >
            <el-table-column type="selection" width="45"></el-table-column>
            <el-table-column label="序号" show-overflow-tooltip width="60">
              <template slot-scope="scope">
                <span
                  >{{
                    scope.$index + (optionCurrentPage - 1) * optionPageSize + 1
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="文件名称"
              prop="fileName"
              show-overflow-tooltip
              width="120"
            >
              <template slot="header">
                <span>文件名称</span>
                <!-- <mine-table-search
                  @searchSubmit="searchOptionSubmit"
                  name="fileName"
                ></mine-table-search> -->
              </template>
            </el-table-column>
            <el-table-column
              label="生成次数"
              prop="counts"
              show-overflow-tooltip
              width="100"
            >
            </el-table-column>
            <el-table-column
              label="版本号"
              prop="version"
              show-overflow-tooltip
              width="100"
            >
            </el-table-column>
            <el-table-column
              label="上传时间"
              prop="updateTime"
              show-overflow-tooltip
            >
              <template slot="header">
                <span>上传时间</span>
              </template>
            </el-table-column>
            <el-table-column width="120px" label="操作">
              <template slot-scope="scope">
                <!-- <mine-button type="text" @click="checkOption(scope.row)"
                  >详情</mine-button
                > -->
                <mine-button
                  style="margin-right: 10px"
                  type="text"
                  @click="download(scope.row)"
                  >下载</mine-button
                >
                <mine-button type="text" @click="algoCut(scope.row)"
                  >规则配置</mine-button
                >
              </template>
            </el-table-column>
          </el-table>
          <mine-pagination
            @numberChange="optionNumberChange"
            :total="optionTotal"
            :page-size="optionPageSize"
            :current-page="optionCurrentPage"
          >
          </mine-pagination>
        </div>
      </div>
    </div>
    <!-- 弹框区 -->
    <el-dialog
      :visible.sync="algoCutVisible"
      :width="'600px'"
      title="算法裁剪"
      @close="close"
    >
      <Algo-cut
        v-if="algoCutVisible"
        @close="close"
        :algoCutRowid="algoCutRowid"
        :algoCutTemplateId="algoCutTemplateId"
      ></Algo-cut>
    </el-dialog>
  </div>
</template>

<script>
import qs from "qs";
import AlgoCut from "./components/algoCutDialog.vue";
import { async } from "@antv/x6/lib/registry/marker/main";

export default {
  components: {
    AlgoCut,
  },
  data() {
    return {
      tableHeight: window.innerHeight - 330,
      // left-table参数
      dictListQuery: { type: 1 }, // 这里type为设1, 标记为诊断页面，为2，标记为预测页面
      dictTableData: [],
      detectTotal: 0,
      dictPageSize: 10,
      dictCurrentPage: 1,
      dictMultipleSelection: [],
      dictLoading: false,

      // right-table参数
      optionListQuery: { type: 1 },
      optionTableData: [],
      optionTotal: 0,
      optionPageSize: 10,
      optionCurrentPage: 1,
      optionMultipleSelection: [],
      optionLoading: false,
      algoCutVisible: false, // 算法裁剪弹框
      algoCutRowid: "", // 算法裁剪当前当行id
      algoCutTemplateId: "", //
      currentDetectLeftRowId: "", // 左列表选中项的id
      timer: null, // 刷新数据的定时器
    };
  },
  watch: {
    "$route.query.rowId": {
      handler(val) {
        if (val) {
          this.loadOptionData(true, false, val);
        }
      },
      immediate: true,
    },
  },
  methods: {
    searchDictSubmit(value) {
      if (value.key === "algoName") {
        this.dictListQuery.algoName = value.value;
      }
      if (value.key === "algoCode") {
        this.dictListQuery.algoCode = value.value;
      }
      if (value.key === "language") {
        this.dictListQuery.language = value.value;
      }
      if (value.key === "purpose") {
        switch (value.value) {
          case "否":
            this.dictListQuery.purpose = 0;
            break;
          case "是":
            this.dictListQuery.purpose = 1;
            break;
        }
      }
      this.loadDictData(true);
    },
    searchOptionSubmit(value) {
      if (value.key === "fileName") {
        this.optionListQuery.fileName = value.value;
      }
      if (value.key === "counts") {
        this.optionListQuery.counts = value.value;
      }
      this.loadOptionData(true);
    },
    async loadData(flag) {
      await this.loadDictData(flag);
      // await this.loadOptionData(flag);
    },
    addDict() {
      // this.$store.commit("SET_DICT_NUMBER", Number(this.detectTotal));
      // detectTotal: Number(this.detectTotal),
      this.$router.push({
        path: "/code/addDetect",
        query: {
          detectTotal: Number(this.detectTotal),
        },
      });
    },
    async deleteDict() {
      this.$mineConfirm("确认要删除", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const ids = this.dictMultipleSelection.map((item) => item.id);
          // .join(",");
          this.dictLoading = true;
          if (this.$webview2.isWPF) {
            const uuid = this.$webview2.generateRandomUUID();
            await this.$webview2.sendWebView2(
              `/algoTemplateFile/deleteByIds${this.$webview2.convertIdsToQueryString(
                ids
              )}`,
              "post",
              "application/json;charset=UTF-8",
              {
                type: 1,
              },
              false,
              uuid
            );
            await window.chrome.webview.addEventListener(
              "message",
              async (e) => {
                let res = e.data.response;
                // TODO： 定制后台数据处理
                if (res.status === 200 && e.data.webInfo.requestId == uuid) {
                  this.$message.success("删除成功");
                  await this.loadData(true);
                } else {
                  this.$message.error(res.msg || "删除失败");
                }
                this.dictLoading = false;
              },
              { once: true }
            );
          } else {
            try {
              const res = await this.$store.dispatch("detectBatchDelete", {
                ids: ids,
                type: 1,
              });
              const result = res.data || {};
              if (result.success) {
                this.$message.success("删除成功");
                await this.loadData(true);
              } else {
                this.$message.error(result.msg || "删除失败");
              }
            } catch (e) {
              console.error(e);
            }
            this.dictLoading = false;
          }
        })
        .catch(() => {});
    },
    async loadDictData(flag, refresh = false) {
      if (flag) {
        this.dictCurrentPage = 1;
      }
      if (refresh) {
        this.dictListQuery = {};
      }
      const params = {
        ...this.dictListQuery,
        page: this.dictCurrentPage,
        pageSize: this.dictPageSize,
        type: 1,
      };
      this.dictLoading = true;
      if (this.$webview2.isWPF) {
        await this.$webview2.sendWebView2(
          "/algoTemplateFile/pageList",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(params, { indices: false }),
          true
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200) {
              this.dictTableData = res.data.list ? res.data.list : [];
              this.detectTotal = res.data.rowCount || 0;
            } else {
              this.dictTableData = [];
              this.total = 0;
            }
            this.dictLoading = false;
          },
          { once: true }
        );
      } else {
        try {
          const res = await this.$store.dispatch(
            "detectPageList",
            qs.stringify(params, { indices: false })
          );
          const result = res.data || {};
          // TODO： 定制后台数据处理
          if (result.success) {
            const data = result.data;
            this.dictTableData = data.list ? data.list : [];
            this.detectTotal = data.rowCount || 0;
          } else {
            this.dictTableData = [];
            this.total = 0;
          }
        } catch (e) {
          console.error(e);
        }
        this.dictLoading = false;
      }
    },
    addOption() {
      if (!this.$store.state.codeDetect.currentDetectLeftRowId)
        return this.$message.warning("请先选择算法！");
      //   this.$store.commit("SET_OPTION_NUMBER", Number(this.optionTotal));
      this.$router.push({
        path: "/code/addAlgoFile",
      });
    },
    async deleteOption() {
      this.$mineConfirm("确认要删除", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const ids = this.optionMultipleSelection.map((item) => item.id);
          this.optionLoading = true;
          if (this.$webview2.isWPF) {
            await this.$webview2.sendWebView2(
              `/algoVersionFile/deleteByIds${this.$webview2.convertIdsToQueryString(
                ids
              )}`,
              "post",
              "application/json;charset=UTF-8",
              {
                type: 1,
              },
              { indices: false },
              false
            );
            await window.chrome.webview.addEventListener(
              "message",
              async (e) => {
                let res = e.data.response;
                // TODO： 定制后台数据处理
                if (res.status === 200) {
                  this.$message.success("删除成功");
                  await this.loadData(true);
                } else {
                  this.$message.error(res.msg || "删除失败");
                }
                this.optionLoading = false;
              },
              { once: true }
            );
          } else {
            try {
              const res = await this.$store.dispatch("algoFileBatchDelete", {
                ids: ids,
              });
              const result = res.data || {};
              if (result.success) {
                this.$message.success("删除成功");
                await this.loadData(true);
              } else {
                this.$message.error(result.msg || "删除失败");
              }
            } catch (e) {
              console.error(e);
            }
            this.optionLoading = false;
          }
        })
        .catch(() => {});
    },
    async loadOptionData(flag, refresh = false, dictId = "") {
      // 如果没有算法id就不执行
      if (!this.$store.state.codeDetect.currentDetectLeftRowId) return;

      if (flag) {
        this.optionCurrentPage = 1;
      }
      if (refresh) {
        this.optionListQuery = {};
      }
      const params = {
        ...this.optionListQuery,
        templateId: dictId,
        page: this.optionCurrentPage,
        pageSize: this.optionPageSize,
      };
      this.optionLoading = true;
      if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/algoVersionFile/pageList",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(params, { indices: false }),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.optionTableData =
                res.data.list && res.data.list.length ? res.data.list : [];
              this.optionTotal = res.data.rowCount || 0;
            } else {
              this.optionTableData = [];
              this.optionTotal = 0;
            }
            this.optionLoading = false;
          },
          { once: true }
        );
      } else {
        try {
          const res = await this.$store.dispatch(
            "algoFileList",
            qs.stringify(params, { indices: false })
          );
          const result = res.data || {};
          // TODO： 定制后台数据处理
          if (result.success) {
            const data = result.data;
            this.optionTableData =
              data.list && data.list.length ? data.list : [];
            this.optionTotal = data.rowCount || 0;
          } else {
            this.optionTableData = [];
            this.optionTotal = 0;
          }
        } catch (e) {
          console.error(e);
        }
        this.optionLoading = false;
      }
    },
    // 查看详情
    checkDict(val) {
      this.$router.push({
        path: "/dictDetail",
        query: {
          id: val.id,
        },
      });
    },
    // checkOption(val) {
    //   this.$store.commit("SET_ALGOFILELISTROWDATA", val);
    //   this.$router.push({
    //     path: "/code/addAlgoFile",
    //     query: {
    //       isEdit: true,
    //     },
    //   });
    // },
    // 多选
    handleDictSelectionChange(selection) {
      this.dictMultipleSelection = selection;
    },
    handleOptionSelectionChange(selection) {
      this.optionMultipleSelection = selection;
    },
    dictNumberChange(val) {
      switch (val.flag) {
        case "pageSize":
          this.dictPageSize = val.pageSize;
          this.loadDictData(true);
          break;
        case "currentPage":
          this.dictCurrentPage = val.currentPage;
          this.loadDictData(false);
          break;
        default:
          break;
      }
    },
    optionNumberChange(val) {
      switch (val.flag) {
        case "pageSize":
          this.optionPageSize = val.pageSize;
          this.loadOptionData(true);
          break;
        case "currentPage":
          this.optionCurrentPage = val.currentPage;
          this.loadOptionData(false);
          break;
        default:
          break;
      }
    },
    // table格式化部分
    isSystemFormatter(row) {
      if (row.purpose === 1) {
        return "否";
      } else {
        return "是";
      }
    },
    // table事件
    dictRowClick(row) {
      this.currentDetectLeftRowId = row.id;
      this.$store.commit("SET_CURRENTDETECTLEFTROWID", row.id);
      this.loadOptionData(true, false, row.id);
    },
    dictOptionClick(row) {},
    // 代码诊断列表编辑
    editDetectList(data) {
      // 存储当前行的数据并跳转路由
      this.$store.commit("SET_DETECTLISTROWDATA", data);
      this.$router.push({
        path: "/code/addDetect",
        query: {
          isEdit: true,
        },
      });
    },
    // 算法文件下载
    async download(record) {
      if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/algoVersionFile/download?id=${record.id}&type=1`,
          "post",
          "application/json;charset=UTF-8",
          {},
          false,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.success) {
              // 文件下载
              this.drawerSwitch = false;
            } else {
              this.$message.error("裁剪生成失败");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("algoFileBatchDownload", {
          id: record.id,
          type: 1,
        });
      }
    },
    // 算法裁剪
    async algoCut(record) {
      this.algoCutTemplateId = record.templateId;
      this.algoCutRowid = record.id;
      this.algoCutVisible = true;
    },
    // 弹框关闭按钮
    close() {
      this.algoCutVisible = false;
    },
  },
  mounted() {
    this.loadData();
  },
  beforeDestroy() {
    clearInterval(this.timer); // 销毁定时器
  },
};
</script>

<style scoped lang="less">
.template-root-div {
  display: flex;
}

.left-table {
  //   flex: 1;
  width: 50%;
  height: 100%;
}

.right-table {
  //   flex: 1;
  width: 50%;
  height: 100%;
  padding-left: 1%;
}
</style>
